package com.lepu.pasm.wxapi;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;

import com.app.utils.LoginUtil;
import com.app.utils.Setting;
import com.core.lib.application.BaseFragmentActivity;
import com.core.lib.core.ApiClient;
import com.core.lib.core.AsyncRequest;
import com.core.lib.utils.main.AppManager;
import com.core.lib.utils.main.LogUtilBase;
import com.core.lib.widget.MyDialog;
import com.lepu.app.fun.health.activity.HealthWebActivity;
import com.lepu.app.main.pay.bean.WxPayBean;
import com.lepu.app.main.pay.bean.WxPayCallBean;
import com.lepu.app.main.pay.util.PayConst;
import com.lepu.app.widget.CustomTopBarNew;
import com.lepu.app.widget.CustomTopBarNew.OnTopbarNewLeftLayoutListener;
import com.lepu.pasm.R;
import com.tencent.mm.sdk.constants.ConstantsAPI;
import com.tencent.mm.sdk.modelbase.BaseReq;
import com.tencent.mm.sdk.modelbase.BaseResp;
import com.tencent.mm.sdk.modelpay.PayReq;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.IWXAPIEventHandler;
import com.tencent.mm.sdk.openapi.WXAPIFactory;

import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

public class WXPayEntryActivity extends BaseFragmentActivity implements
        IWXAPIEventHandler, AsyncRequest, OnTopbarNewLeftLayoutListener {

    private static final String TAG = "MicroMsg.SDKSample.WXPayEntryActivity";

    private static final String REQUEST_DATA_INFO = "request_data_info";//拿到信息自动去支付
    private static final String REQUEST_DATA_RESULT = "request_data_result";

    private String mTestCode = "";

    // 充值
    private final IWXAPI mMsgApi = WXAPIFactory.createWXAPI(this, null);
    private PayReq mReq = new PayReq();

    private WxPayBean mWxPayBean = null;
    private boolean mIsEnterWxCallBack = false;
    private String mOrderID = "";

    boolean mPaySuccess = false;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.health_pay_layout);

        init();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    @Override
    public void onTopbarLeftLayoutSelected() {
        finish(true);
    }

    @Override
    public void onBackPressed() {
        finish(true);
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
        mMsgApi.handleIntent(intent, this);
    }

    @Override
    public void onReq(BaseReq req) {
    }

    @Override
    public void onResp(BaseResp resp) {
        LogUtilBase.LogD(TAG, "onPayFinish, errCode = " + resp.errCode);

        mIsEnterWxCallBack = true;
        if (resp.errCode == 0) {
            mTestCode = getString(R.string.health_order_tip_success);
            mPaySuccess = true;
        } else if (resp.errCode == -1) {
            mTestCode = getString(R.string.health_order_tip_fail);
        } else if (resp.errCode == -2) {
            mTestCode = getString(R.string.health_order_tip_cancel);
        }

        if (resp.getType() == ConstantsAPI.COMMAND_PAY_BY_WX) {
            //requestGetResult();
        }
    }

    @Override
    public void onResume() {
        super.onResume();

        if (mWxPayBean != null) {
            //下充值订单成功后，再回到这个页面，去查询状态
            requestResult();
        }
    }

    // ============
    private void init() {
        // topbar
        CustomTopBarNew topbar = (CustomTopBarNew) findViewById(R.id.topbar);
        topbar.setTopbarTitle("订单支付");
        topbar.setonTopbarNewLeftLayoutListener(this);

        mTestCode = getString(R.string.health_order_tip_fail);
        mMsgApi.registerApp(PayConst.APP_ID);

        Bundle data = getIntent().getExtras();
        int type = 0;
        if (data != null && data.size() > 0) {
            mOrderID = data.getString("order_id");
            type = data.getInt("type");
        }

        requestDataInfo(type);
    }

    /**
     * 获取订单信息
     */
    public void requestDataInfo(int type) {

        showProgressDialog();

        String url = "";
        if (type == HealthWebActivity.TYPE_ORDER_PEI_ZHEN) {
            url = Setting.getHealthPeiZhenOrderInfoUrl();
        } else {
            url = Setting.getHealthZhuanZhenOrderInfoUrl();
        }

        Map<String, Object> map = new HashMap<String, Object>();
        JSONObject params = new JSONObject();
        try {
            params.put("DeviceID", Setting.DEVICEID);
            params.put("ApplicationID", Setting.APPLICATIONID);

            params.put("UserID", LoginUtil.getUserId());
            params.put("LoginToken", LoginUtil.getLoginToken());

            if (type == HealthWebActivity.TYPE_ORDER_PEI_ZHEN) {
                params.put("OrderID", mOrderID);
            } else {
                params.put("OrderNumber", mOrderID);
            }

            params.put("PayType", "APP");

        } catch (Exception e) {
        }
        map.put("ht", params);

        ApiClient.http_post_main(url, map, null, this, REQUEST_DATA_INFO,
                false);
    }

    /**
     * 获取支付结果
     */
    public void requestResult() {

        showProgressDialog();

        String url = Setting.getHealthOrderResultUrl();

        Map<String, Object> map = new HashMap<String, Object>();
        JSONObject params = new JSONObject();
        try {
            params.put("DeviceID", Setting.DEVICEID);
            params.put("ApplicationID", Setting.APPLICATIONID);

            params.put("UserID", LoginUtil.getUserId());
            params.put("LoginToken", LoginUtil.getLoginToken());

            params.put("TradeNo", mWxPayBean.TradeNo);

        } catch (Exception e) {
        }
        map.put("ht", params);

        ApiClient.http_post_main(url, map, null, this, REQUEST_DATA_RESULT,
                false);
    }

    public void sendWxPay() {

        try {
            String appId = mWxPayBean.AppID;
            mReq.appId = appId;
            mReq.partnerId = mWxPayBean.PartnerID;
            mReq.prepayId = mWxPayBean.PrepayID;
            mReq.packageValue = mWxPayBean.Package;
            mReq.nonceStr = mWxPayBean.Noncestr;
            mReq.timeStamp = mWxPayBean.Timestamp;
            mReq.sign = mWxPayBean.Sign;

            mMsgApi.registerApp(appId);
            boolean flag = mMsgApi.sendReq(mReq);
            LogUtilBase.LogD(null, "pay  " + String.valueOf(flag));
            if (flag) {
                //如果微信没有登录，可能会返回false
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * order success
     */
    public void getPaySuccess() {
        LogUtilBase.LogD(null, mTestCode);

        HealthWebActivity instance = (HealthWebActivity) AppManager.getAppManager().getActivity(HealthWebActivity.class);
        if (instance != null) {
            instance.jumpOrderSuccessDialog(mOrderID);
        }

        finish(true);
    }

    /**
     * order fail
     */
    public void getPayFail() {

        if (!mIsEnterWxCallBack) {
            mTestCode = getString(R.string.health_order_tip_fail);
        }

        LogUtilBase.LogD(null, mTestCode);

        HealthWebActivity instance = (HealthWebActivity) AppManager.getAppManager().getActivity(HealthWebActivity.class);
        if (instance != null) {
            instance.jumpOrderFailDialog(mTestCode);
        }

        finish(true);
    }

    @Override
    public void RequestComplete(Object object, Object data) {
        if (object.equals(REQUEST_DATA_INFO)) {
            hideProgressDialog();

            mWxPayBean = WxPayBean.parseJsonData((String) data);
            sendWxPay();

        } else if (object.equals(REQUEST_DATA_RESULT)) {
            hideProgressDialog();
            // SUCCESS FAIL
            WxPayCallBean item = WxPayCallBean.parseJsonData((String) data);
            if (mPaySuccess || (!TextUtils.isEmpty(item.TradeState)
                    && item.TradeState.equals("SUCCESS"))) {
                getPaySuccess();
            } else {
                getPayFail();
            }
        }
    }

    @Override
    public void RequestError(Object object, int errorId, String errorMessage) {
        if (object.equals(REQUEST_DATA_INFO)) {
            hideProgressDialog();

            getPayFail();
        } else if (object.equals(REQUEST_DATA_RESULT)) {
            hideProgressDialog();

            if (mPaySuccess) {
                getPaySuccess();
            } else {
                getPayFail();
            }
        }
    }
}